package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.acct.facade.request.VirtAcctBalanceQueryRequest;
import cc.rengu.igas.acct.facade.response.VirtAcctBalanceQueryResponse;
import cc.rengu.igas.acct.facade.result.Result;
import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.constant.DubboMethodConstant;
import cc.rengu.igas.bsps.common.dao.BspsMchntFeeInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntFeeInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntFeeInfo;
import cc.rengu.igas.bsps.common.enums.FeeTypeEnum;
import cc.rengu.igas.bsps.common.enums.MchntTypeEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.MchntAcctBalanceQueryRequest;
import cc.rengu.igas.bsps.facade.response.MchntAcctBalanceQueryResponse;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.util.Optional;

/**
 * 商户待结算余额查询.
 *
 * @author zhangxuran (联调修改)
 * @version 1.0
 * @date 2020.04.13
 */
public class MchntAcctBalanceQueryService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntAcctBalanceQueryRequest mchntAcctBalanceQueryRequest = new MchntAcctBalanceQueryRequest();
        ConvertUtil.convertOutput(mchntAcctBalanceQueryRequest);
        return mchntAcctBalanceQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        BizResponse<MchntAcctBalanceQueryResponse> bizResponse = new BizResponse<>();
        MchntAcctBalanceQueryResponse mchntAcctBalanceQueryResponse = new MchntAcctBalanceQueryResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntAcctBalanceQueryResponse);
        MchntAcctBalanceQueryRequest mchntAcctBalanceQueryRequest = (MchntAcctBalanceQueryRequest) request;
        String instId = mchntAcctBalanceQueryRequest.getHeader().getInstId();
        String mchntNo = mchntAcctBalanceQueryRequest.getMchntNo();
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(mchntNo)) {
            rglog.error("参数必填性校验失败！instId:<{}>,mchntNo:<{}>", instId, mchntNo);
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(instId, mchntNo);
        if (null == mchntInfo) {
            rglog.error("获取商户信息失败,mchntNo:<{}>", mchntNo);
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        //连锁商户门店非独立维护,无虚拟账户,不查询余额
        if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntInfo.getMchntType()) && AppParamConstant.NO.equals(mchntInfo.getIndependentDataFlag())) {
            rglog.debug("连锁商户门店非独立维护,无虚拟账户,不查询余额,返回默认值.");
            mchntAcctBalanceQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            mchntAcctBalanceQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            mchntAcctBalanceQueryResponse.setAcctBalance("");
            mchntAcctBalanceQueryResponse.setAvailableBalance("");
            mchntAcctBalanceQueryResponse.setFreezeBalance("");
            mchntAcctBalanceQueryResponse.setWithdrawalFeeRate("");
            mchntAcctBalanceQueryResponse.setCashWithdrawalFlag(AppParamConstant.NO);
            return bizResponse;
        }

        Optional<ChannelCallCfg> channelCallCfgOptional = txnInfo.getChannelCallCfgList().stream().filter(item -> ChannelEnum.ACCT.getChannelType().equals(item.getCallChannelId())).findFirst();
        if (!channelCallCfgOptional.isPresent()) {
            rglog.error("通道服务调用配置表无虚拟账户通道的配置数据！,instId:<{}>,traceNo:<{}>,", instId, mchntAcctBalanceQueryRequest.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespCode(), RespCodeEnum.CHANNEL_CONFIG_NOT_EXIST.getRespDesc());
        }
        //获取通道服务调用配置
        ChannelCallCfg channelCallCfg = channelCallCfgOptional.get();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);

        VirtAcctBalanceQueryRequest virtAcctBalanceQueryRequest = new VirtAcctBalanceQueryRequest();
        ConvertUtil.convertOutput(virtAcctBalanceQueryRequest);
        cc.rengu.igas.acct.facade.base.Header header = new cc.rengu.igas.acct.facade.base.Header();
        header.setInstId(mchntAcctBalanceQueryRequest.getHeader().getInstId());
        header.setTxnNum(channelCallCfg.getCallChannelTxn());
        header.setTraceNo(sysSeqNum);
        header.setSrcSysId(AppParamConstant.SYS_ID);
        header.setChanlId(BspsAppParamConstant.BSP_SYS_ID);
        header.setTransTime(DateUtil.getCurrentTime());
        header.setTransDate(DateUtil.getCurrentDate());
        virtAcctBalanceQueryRequest.setHeader(header);
        //userType : 00-商户  01-会员 02-营销
        virtAcctBalanceQueryRequest.setUserType("00");
        virtAcctBalanceQueryRequest.setUserId(mchntInfo.getMchntNo());
        //虚拟账户
        virtAcctBalanceQueryRequest.setAcctType("00");
        DubboService dubboService = new DubboServiceImpl();
        Result<VirtAcctBalanceQueryResponse> acctDubboResult = (Result<VirtAcctBalanceQueryResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_VIRT_ACCT_SERVICE, "virtAcctBalanceQuery", virtAcctBalanceQueryRequest);
        if (null == acctDubboResult) {
            bizResponse.setRespCode(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
            bizResponse.setRespDesc(OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
            bizResponse.setResult(mchntAcctBalanceQueryResponse);
            return bizResponse;
        } else {
            if (!acctDubboResult.isSuccess() || !BspsAppParamConstant.DUBBO_SUCCESS.equals(acctDubboResult.getResult().getRespCode())) {
                bizResponse.setRespCode(acctDubboResult.getResult().getRespCode());
                bizResponse.setRespDesc(acctDubboResult.getResult().getRespCode());
                mchntAcctBalanceQueryResponse.setRespCode(acctDubboResult.getResult().getRespCode());
                mchntAcctBalanceQueryResponse.setRespDesc(acctDubboResult.getResult().getRespDesc());
                bizResponse.setResult(mchntAcctBalanceQueryResponse);
                return bizResponse;
            } else {
                mchntAcctBalanceQueryResponse.setAcctBalance(acctDubboResult.getResult().getAcctBalance());
                mchntAcctBalanceQueryResponse.setAvailableBalance(acctDubboResult.getResult().getAvailableBalance());
                mchntAcctBalanceQueryResponse.setFreezeBalance(acctDubboResult.getResult().getFreezeBalance());
            }
        }

        /*是否开通提现*/
        mchntAcctBalanceQueryResponse.setCashWithdrawalFlag(mchntInfo.getCashWithdrawalFlag());

        /*提现费率*/
        BspsMchntFeeInfoMapper bspsMchntFeeInfoMapper = new BspsMchntFeeInfoMapperImpl();
        String date = DateUtil.getCurrentDate();
        MchntFeeInfo mchntFeeInfo = bspsMchntFeeInfoMapper.selectBspsMchntFeeInfoByPrimaryKey(instId, mchntInfo.getMchntNo(), "00", FeeTypeEnum.DO.getFeeType(), date);
        if (null != mchntFeeInfo) {
            mchntAcctBalanceQueryResponse.setWithdrawalFeeRate(mchntFeeInfo.getFeeRate());
        }

        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntAcctBalanceQueryResponse mchntAcctBalanceQueryResponse = (MchntAcctBalanceQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntAcctBalanceQueryResponse);
    }
}
